const { checkLogin } = require('../common/utils');
const { getBlogList, getBlogDetail, createBlog, updateBlog, deleteBlog } = require('../controller/blog');
const { SuccessModel, ErrorModel } = require('../model/responseModel');


const handleBlogRouter = (req, res) => {
    const method = req.method;
    const path = req.path;
    const query = req.query || {};

    if (method === 'GET' && path === '/api/blog/list') {
        const { author = '', keyword = '' } = query;
        return getBlogList(author, keyword).then(listData => {
            return new SuccessModel(listData);
        }).catch(e => {
            console.error(e);
        });
    } else if (method === 'GET' && path === '/api/blog/detail') {
        const { id } = query;
        return getBlogDetail(id).then(data => {
            return new SuccessModel(data);
        }).catch(e => {
            console.error(e);
        });
    }

    if (method === 'POST' && path === '/api/blog/new') {
        return checkLogin(req).then(loginStatus => {
            if (!loginStatus) {
                return new ErrorModel('尚未登录');
            };
            return createBlog(req.body).then(data => new SuccessModel(data)).catch(e => {
                console.error(e);
            });
        });
    } else if (method === 'POST' && path === '/api/blog/update') {
        return updateBlog(req.body.id, req.body).then(val => val ? new SuccessModel() : new ErrorModel('更新博客失败'));
    } else if (method === 'POST' && path === '/api/blog/delete') {
        return deleteBlog(req.body.id, req.body.author).then(val => val ? new SuccessModel() : new ErrorModel('删除博客失败'));
    }
};

module.exports = handleBlogRouter;
